<?php
/**
 * @author Tongle Xu <xutongle@gmail.com>
 * @copyright Copyright (c) 2003-2103 Jinan TintSoft development co., LTD
 * @license http://www.tintsoft.com/html/about/copyright/
 * @version $Id$
 */
namespace Leaps\Leaps;

use Leaps;
use Leaps\Base\Action;
use Leaps\Base\InlineAction;
use Leaps\Base\InvalidRouteException;

/**
 * Api类的基类。
 *
 * @author Tongle Xu <xutongle@gmail.com>
 * @since 4.0
 */
class Controller extends \Leaps\Base\Controller
{
	/**
	 * @var boolean whether to run the command interactively.
	 */
	public $interactive = true;


	/**
	 * Runs an action with the specified action ID and parameters.
	 * If the action ID is empty, the method will use [[defaultAction]].
	 * @param string $id the ID of the action to be executed.
	 * @param array $params the parameters (name-value pairs) to be passed to the action.
	 * @return integer the status of the action execution. 0 means normal, other values mean abnormal.
	 * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
	 * @see createAction
	 */
	public function runAction($id, $params = [])
	{
		if (!empty($params)) {
			$options = $this->globalOptions();
			foreach ($params as $name => $value) {
				if (in_array($name, $options, true)) {
					$this->$name = $value;
					unset($params[$name]);
				}
			}
		}
		return parent::runAction($id, $params);
	}

	/**
	 * 将参数绑定到行动。
	 * This method is invoked by [[Action]] when it begins to run with the given parameters.
	 * This method will first bind the parameters with the [[globalOptions()|global options]]
	 * available to the action. It then validates the given arguments.
	 * @param Action $action the action to be bound with parameters
	 * @param array $params the parameters to be bound to the action
	 * @return array the valid parameters that the action can run with.
	 * @throws Exception if there are unknown options or missing arguments
	 */
	public function bindActionParams($action, $params)
	{
		$args = [];
		if (!empty($params)) {
			$options = $this->globalOptions();
			foreach ($params as $name => $value) {
				if (in_array($name, $options, true)) {
					$this->$name = $value;
				} elseif (is_int($name)) {
					$args[] = $value;
				} else {
					throw new Exception(Leaps::t('leaps', 'Unknown option: --{name}', ['name' => $name]));
				}
			}
		}

		if ($action instanceof InlineAction) {
			$method = new \ReflectionMethod($this, $action->actionMethod);
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}

		$missing = [];
		foreach ($method->getParameters() as $i => $param) {
			$name = $param->getName();
			if (!isset($args[$i])) {
				if ($param->isDefaultValueAvailable()) {
					$args[$i] = $param->getDefaultValue();
				} else {
					$missing[] = $name;
				}
			}
		}

		if (!empty($missing)) {
			throw new Exception(Leaps::t('leaps', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
		}

		return $args;
	}



}
